<template>
  <el-container>
    <!-- v-loading="loading" -->
    <el-header>
      <h2>值班前准备</h2>
    </el-header>
    <el-main>
      <el-card shadow="hover">
        <div slot="header">
          <span>人员设置</span>
        </div>
        <config-panel
          v-if="!stateChanged"
          :selected="clientSelected"
          :range="rangeSelected"
          @set="handleSet"
        />
      </el-card>
      <br />
      <el-card shadow="hover">
        <el-row slot="header" type="flex" align="middle">
          <el-col :span="12" style="text-align:left">
            <el-badge :value="clientSelected.length" style="padding-right:10px">
              当前值班
            </el-badge>
          </el-col>
          <!-- <el-col :span="12" style="text-align:right">
            <el-badge type="primary" :value="clientChecked.length">
              <el-button size="small" @click="handleDelete">删除</el-button>
            </el-badge>
          </el-col> -->
        </el-row>
        <summary-table
          @stroke="handleStroke"
          @check="handleCheck"
          ref="summaryTable"
        />
      </el-card>
      <el-dialog
        :show-close="false"
        :visible.sync="showDetail"
        top="-30px"
        :width="detailModelWidth"
      >
        <detail-view v-if="showDetail" />
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
import SummaryTable from "./components/SummaryTable";
import ConfigPanel from "./components/ConfigPanel";
import DetailView from "./components/DetailView";
export default {
  components: {
    SummaryTable,
    ConfigPanel,
    DetailView,
  },
  computed: {
    source() {
      return this.$store.state.summary.rectifySource;
    },
    store() {
      return this.$store.state.summary.attention;
    },
    bodyWidth() {
      return this.$store.state.view.body.size.width;
    },
    detailModelWidth() {
      // config
      let minWidth = 600;
      let maxWidth = 800;
      let widthRatio = 0.6;
      // calculate
      if (this.bodyWidth < minWidth) {
        return this.bodyWidth.toString() + "px";
      } else if (this.bodyWidth * widthRatio < minWidth) {
        return minWidth.toString() + "px";
      } else if (this.bodyWidth * widthRatio > maxWidth) {
        return maxWidth.toString() + "px";
      } else {
        return (widthRatio * 100).toString() + "%";
      }
    },
  },
  data() {
    return {
      clientSelected: [],
      clientChecked: [],
      rangeSelected: "180days",
      clientStroked: "",
      detailType: "rectify",
      refreshCode: 0,
      lastChange: 0,
      stateChanged: false,
      showDetail: false,
      loading: true,
    };
  },
  methods: {
    handleRefresh() {
      this.stateChanged = true;
      this.$nextTick(() => {
        this.stateChanged = false;
      });
    },
    handleClearCheck() {
      if (this.$refs.summaryTable) {
        this.$refs.summaryTable.$refs.mainTable.clearSelection();
      }
    },
    handleCheck(val) {
      this.clientChecked = val;
    },
    handleDelete() {
      if (this.clientChecked.length === 0) return;
      this.$confirm(
        "<p>确定删除已勾选的 <b>" +
          this.clientChecked.length.toString() +
          "</b> 位值班人员吗？</p>",
        {
          dangerouslyUseHTMLString: true,
          type: "info ",
          showClose: false,
          center: true,
        }
      )
        .then(() => {
          // console.log("handleDelete");
          let newList = [];
          for (let i = 0; i < this.clientSelected.length; i++) {
            if (this.clientChecked.indexOf(this.clientSelected[i][2]) === -1) {
              newList.push(this.clientSelected[i]);
            }
          }
          this.clientSelected = newList;
          this.saveStore();
          this.saveState();
          this.handleClearCheck();
          this.handleRefresh();
        })
        .catch(() => {});
    },
    handleSet({ clientSelected, rangeSelected }) {
      this.clientSelected = clientSelected;
      this.rangeSelected = rangeSelected;
      this.saveStore();
      this.saveState();
    },
    handleStroke({ client, type }) {
      this.clientStroked = client;
      this.detailType = type;
      this.$nextTick(() => {
        this.showDetail = true;
      });
      this.saveStore();
      // this.saveState();
    },

    loadStore() {
      if (this.store.clientSelected.length > 0) {
        this.clientSelected = this.store.clientSelected;
      }
      if (this.store.clientStroked.length > 0) {
        this.clientStroked = this.store.clientStroked;
      }
      if (this.store.detailType.length > 0) {
        this.detailType = this.store.detailType;
      }
      if (this.store.rangeSelected.length > 0) {
        this.rangeSelected = this.store.rangeSelected;
      }
      if (this.store.lastChange > 0) {
        this.lastChange = this.store.lastChange;
      }
      // clear checked
      // this.clientChecked = [];
      this.handleClearCheck();
    },
    saveStore() {
      this.$store.commit("summary/SAVE_ATTENTION", {
        clientSelected: this.clientSelected,
        clientStroked: this.clientStroked,
        rangeSelected: this.rangeSelected,
        detailType: this.detailType,
        lastChange: this.lastChange,
      });
      // if (saveState) this.saveState();
    },

    loadState() {
      // console.log("loadState");
      this.loading = true;
      this.axios
        .post("api/state_load/", {
          model: "concern",
          user: this.$store.getters.userbase,
          time: this.lastChange,
        })
        .then((response) => {
          // console.log(response.data);
          if (response.data.status === 1) {
            let content = response.data.content;
            let value = JSON.parse(content.value);
            this.clientSelected = value.clientSelected;
            // this.clientStroked = value.clientStroked;
            // this.rangeSelected = value.rangeSelected;
            // this.detailType = value.detailType;
            this.lastChange = content.time;
            let lastChange = new Date(content.time);
            this.$notify({
              title: "数据已由 " + content.username + " 更新",
              message: "于 " + lastChange.toLocaleString(),
              type: "success",
            });
            this.saveStore();
            this.handleClearCheck();
            this.handleRefresh();
          } else if (response.data.status === -1) {
            this.saveState();
          }
          this.loading = false;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    saveState() {
      // this.handleRefresh();
      this.lastChange = new Date().getTime();
      this.axios
        .post("api/state_save/", {
          value: JSON.stringify({
            clientSelected: this.clientSelected,
            // clientStroked: this.clientStroked,
            // rangeSelected: this.rangeSelected,
            // detailType: this.detailType,
          }),
          model: "concern",
          user: this.$store.getters.userbase,
          time: this.lastChange,
        })
        .then((/*response*/) => {
          // console.log(response.data);
          /*
          this.$notify({
            // title: "数据已由 " + this.$store.getters.userbase.name + " 更新",
            title: "数据已由 您 更新",
            message: "于 " + new Date().toLocaleString(),
            type: "success",
          });
          */
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
  created() {
    let that = this;
    this.loadStore();
    this.loadState();
    this.refreshCode = setInterval(() => {
      that.loadState();
    }, 5000);
  },
  mounted() {
    // console.log(this.$refs.summaryTable);
  },
  beforeDestroy() {
    let refreshCode = this.refreshCode;
    clearInterval(refreshCode);
  },
};
</script>
